//
//  HMEditView.swift
//  HealthMonitoring
//
//  Created by YTYanK on 04/01/2019.
//  Copyright © 2019 YTYanK. All rights reserved.
//
//   这里是一个 编辑view

import UIKit
import SwiftyJSON

class HMEditView: UIView {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
     
    */
    
    enum EditType: String {
        case pressure = "血压"
        case weight = "体重"
        case heat = "体温"
        case heart_rate = "心率"
        case sugar = "血糖"
    }

    
//    var edit_type = ""
//    var edit_t
    private var buttonAry = Array<UIButton>()
    private var fieldAry = Array<UITextField>()
    private var  fieldIndex = 0
    private var urlID = ""
    private var buttonType = 0  //按钮类型
    var hiddenView: ((_ view: HMEditView) ->())?
    var saveData: ((_ data: JSON) ->())?
    var removeData: ((_ data: JSON?) ->())?
    private var edit_type = EditType.pressure
    override init(frame: CGRect) {
       super.init(frame: frame)
    }

    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // 类型， frmae, 数据
    convenience init(id: String, frame: CGRect, data: JSON) {
        self.init(frame: frame)
        //["blood-pressure-all", "weight-all", "body-temp-all","heart-rate-all","blood-glucose-all"]
        let type = EditType.self
        if id == "blood-pressure-all" {
            
            self.edit_type  = type.pressure
        }else if id == "weight-all" {
             self.edit_type  = type.weight
        }else if id == "body-temp-all" {
             self.edit_type = type.heat
        }else if id == "heart-rate-all" {
            self.edit_type = type.heart_rate
        }else if id == "blood-glucose-all" {
            self.edit_type = type.sugar
        }
        
        
        self.urlID = id
        
        self.initView(type: self.edit_type.rawValue, values: data)
    }

    func initView(type: String?, values: JSON) {

        
        self.frame = CGRect.init(x: 0, y: 0, width: configure.shareConfigure.screenWidth, height: configure.shareConfigure.screenHeight)
        self.backgroundColor = UIColor.RGBA(r: 0, g: 0, b: 0, a: 0.2)
        let y = configure.shareConfigure.screenHeight/2 - 220
        let x = configure.shareConfigure.screenWidth/2 - (configure.shareConfigure.screenWidth - 100)/2
        let subView = UIView.init(frame: CGRect.init(x: x, y: y, width: configure.shareConfigure.screenWidth - 100, height: 300))
        subView.layer.cornerRadius = 8
        subView.layer.masksToBounds = true
        

        for i in 0..<values.count {
            if values[i]["Button"] != nil {
                for  k in 0..<values[i]["Button"].count {
                  let but = UIButton.init(frame: CGRect.init(x: 20 + (10 * k) + (k * 100), y: 80, width: 100, height: 44))
                    let str = values[i]["Button"][k].stringValue
                    but.layer.cornerRadius = 8
                    but.setTitle(str, for: UIControlState.normal)
                    but.layer.borderWidth = 1
                    but.tag = k + 1
                    
                    if values[i]["selected"].intValue  ==  (k + 1) {
                        but.isSelected = true
                        but.backgroundColor = configure.shareConfigure.HMColor1
                        but.layer.borderColor = but.backgroundColor?.cgColor
                        self.buttonType = (k + 1) //默认值
                    }else {
                        but.isSelected = false
                        but.backgroundColor = UIColor.white
                    }
                    but.setTitleColor(UIColor.white, for: UIControlState.selected)
                    but.setTitleColor(UIColor.black, for: UIControlState.normal)
                    but.addTarget(self, action: #selector(selectChangend), for: UIControlEvents.touchUpInside)
                    subView.addSubview(but)
                    self.buttonAry.append(but)
                }
            }else {
            
            let  dic =  values[i].dictionaryValue
            let label = UILabel.init(frame: CGRect.init(x: 20, y: (i*40 + 10), width: 100, height: 40))
            label.text = dic["label"]?.stringValue
            label.tag = i
            
            
            let field = UITextField.init(frame: CGRect.init(x: 100, y: (i * 40 + 10), width: 120, height: 40))
            field.text = dic["value"]?.stringValue
            field.placeholder = "请输入" + (dic["label"]?.stringValue)!
            field.tag = i
            field.addLayer(isAddLayer: (false, false, false, true), color: UIColor.black, crude: 1, layout: (w: 150, h: 30))
            field.delegate = self
            
            self.fieldAry.append(field)
            subView.addSubview(label)
            subView.addSubview(field)
            }
        }
        
        let radius: CGFloat =  4.0
        
        let save = UIButton()
        save.setTitle("保存", for: .normal)
        save.backgroundColor = configure.shareConfigure.HMColor1
        save.layer.cornerRadius = radius
        subView.addSubview(save)
        save.topAlign(view: subView, predicate: "140")
        save.leadingAlign(view: subView, predicate: "10")
        save.trailingAlign(view: subView, predicate: "-10")
        save.heightConstrain(predicate: "44")
        save.addTarget(self, action: #selector(saveClick), for: UIControlEvents.touchUpInside)

        
        let delete = UIButton()
        delete.setTitle("删除模板", for: .normal)
        delete.backgroundColor = .red
        delete.layer.cornerRadius = radius
        subView.addSubview(delete)
        delete.topVertically(view: save, predicate: "10")
        delete.leadingAlign(view: subView, predicate: "10")
        delete.trailingAlign(view: subView, predicate: "-10")
        delete.heightConstrain(predicate: "44")
        delete.addTarget(self, action: #selector(deleteClick), for: UIControlEvents.touchUpInside)
        

        let cancel = UIButton()
        cancel.setTitle("取消", for: .normal)
        cancel.backgroundColor = UIColor.gray
        cancel.layer.cornerRadius = radius
        subView.addSubview(cancel)
        cancel.topVertically(view: delete, predicate: "10")
        cancel.leadingAlign(view: subView, predicate: "10")
        cancel.trailingAlign(view: subView, predicate: "-10")
        cancel.heightConstrain(predicate: "44")
        cancel.addTarget(self, action: #selector(cancelClick), for: UIControlEvents.touchUpInside)
        
        subView.backgroundColor = UIColor.white
        self.addSubview(subView)
        
    }
    
    
    
    func hidden() {
//        self.removeFromSuperview()
//        self.hiddenView: ((_ view: HMEditView) ->())?
        self.hiddenView?(self)
    }
    
    // 选择按钮
    @objc func selectChangend(sender: UIButton) {
        self.fieldAry[self.fieldIndex].resignFirstResponder()//结束编辑状态
        
        if self.buttonAry.count > 0 {
            for  but  in self.buttonAry {
                if but.tag == sender.tag {
                    
                    but.backgroundColor = configure.shareConfigure.HMColor1
                    but.layer.borderColor = configure.shareConfigure.HMColor1.cgColor
                    but.isSelected = true
                    self.buttonType = but.tag
                }else {
                    but.backgroundColor = UIColor.white
                    but.layer.borderColor = UIColor.black.cgColor
                    but.isSelected = false
                }
            }
        }
    }
    //保存
    @objc func saveClick(sender: UIButton) {
        
        self.fieldAry[self.fieldIndex].resignFirstResponder()//结束编辑状态

        var newAry = Array<String>()
        for i  in 0..<self.fieldAry.count {
            let text = self.fieldAry[i].text
            newAry.append(text!)
        }
        
        if self.edit_type == .weight  || self.edit_type == .heart_rate{
            newAry.append("\(self.buttonType)")
        }
        
        
        self.saveData?(JSON.init(newAry))
        self.hidden()
        
    }
    //删除
    @objc func deleteClick(sender: UIButton) {
        self.fieldAry[self.fieldIndex].resignFirstResponder()//结束编辑状态
        self.removeData?(nil)
        self.hidden()
    }
    // 取消
    @objc func cancelClick(sender: UIButton) {
        self.hidden()
    }
    
    
    
}



extension HMEditView : UITextFieldDelegate {
//    textFieldDidEndEditing
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
//        print("======??开始", textField.tag)
        self.fieldIndex = textField.tag  //选择中的Field.tag
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        print("=====>>>>", textField.text)
        
    }
//    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//        print("======>>>", textField.text, string)
//
//        return true
//    }
}
